package com.mystyle.le.liuxiang.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by le on 2016/10/9.
 */
public class DownData {
    /*
    * 判断是否有无网络
    * */
    public static boolean isNetWorkConn(Context context){
        boolean b1 = false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        if (activeNetworkInfo!=null){
            return activeNetworkInfo.isConnected();//是否联网
        }
        return  b1;
    }


    /*
    * 下载数据
    * */
    public static byte[] downData(String path){
        HttpURLConnection connection = null;
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5*1000);
            connection.connect();
            if (connection.getResponseCode()==200){
                InputStream inputStream = connection.getInputStream();
                outputStream = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len;
                while ((len = inputStream.read(buf))!=-1){
                    outputStream.write(buf,0,len);
                    outputStream.flush();
                }
                return outputStream.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (connection!=null){
                    connection.disconnect();
                }
            }
        }
        return null;
    }
}
